require "RMagick"
class Picture < ActiveRecord::Base

  belongs_to :uploader, :class_name=>"User", :foreign_key=>"user_id"
  
  validates_format_of :content_type, :with=> /^image/,
                      :message=>"文件不是图片格式!"

  def picture=(picture_field)
    self.name=base_part_of(picture_field.original_filename)
    self.content_type = picture_field.content_type.chomp
    self.data = picture_field.read
    img = Magick::Image.from_blob(self.data).first
    scale_factor= img.columns>img.rows ? (60.0/img.rows) : (60.0/img.columns)
    img = img.thumbnail(scale_factor)
    img = img.crop(0, 0, 60, 60)
    self.data=img.to_blob
  end
  
  def before_destroy
    Company.update_all("picture_id = 2" , ["picture_id=?",self.id])
    User.update_all("picture_id = 1" , ["picture_id=?",self.id])
 #  Statistic.destroy_all(["category_id=4 and obj_id=?",self.id])
  end
  
  def base_part_of(file_name)
    name = File.basename(file_name)
    name.gsub(/[^\w._-]/,'')
  end
  
end
